<?php
/**
 * DummyService.php
 * 文件描述 虚拟对象逻辑页
 * Created on 2020/8/31 18:35
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\xiangji\services;



use app\common\caches\LoveQuestionCache;
use app\common\facades\auth\Auth;
use app\Request;
use app\common\helpers\Response;
use app\common\models\LoveQuestion;
use app\xiangji\exception\BadRequestException;
use app\xiangji\exception\ModelNotFoundException;
use app\common\models\LoveQuestionAnswer;
use app\xiangji\exception\ServiceUnavailableException;
use think\facade\Db;

class QuestionService
{
    const ANSWER_QUESTION_SCORE = 5;

    private $loveQuestionModel;
    private $loveQuestionAnswerModel;
    private $user;

    public function __construct(LoveQuestion $loveQuestionModel, LoveQuestionAnswer $loveQuestionAnswerModel)
    {
        $this->user = Auth::guard('api')->user();
        $this->loveQuestionModel = $loveQuestionModel;
        $this->loveQuestionAnswerModel = $loveQuestionAnswerModel;
    }

    public function search(Request $request)
    {
        // 从缓存中获取用户问题列表
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $list = LoveQuestionCache::getUserLoveQuestList($this->user->id, $page, $limit);
        // 无缓存数据则读取数据库数据
        if (!$list){
            $list = $this->loveQuestionModel
                ->with(['answer' => function($query){
                    $query->where('user_id', $this->user->id);
                }])
                ->field(['id', 'question', 'sort', 'create_time', 'update_time'])
                ->order('sort')
                ->paginate([
                    'list_rows' => $request->get('limit', 10),
                    'page' => $request->get('page', 1)
                ])->map(function ($item){
                    $item = $item->toArray();
                    // 洗一遍数据，将只有一条数据的回答数组，提升到父级问题数据中
                    $item['answer'] = $item['answer'][0] ?? null;
                    return $item;
                });
            // 缓存列表数据
            LoveQuestionCache::setUserLoveQuestList($this->user->id, $page, $limit, $list);
        }
        return $list;
    }

    /**
     * @todo 展现问题详情信息
     * @param int $id   问题ID
     * @return array|mixed|\think\Model|null
     * @throws ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function show(int $id)
    {
        // 获取缓存数据
        $question = LoveQuestionCache::getUserLoveQuestById($this->user->id, $id);
        // 无缓存数据读取数据库
        if (!$question){
            $question = $this->loveQuestionModel->with(['answer' => function($query){
                $query->where('user_id', $this->user->id)->field(['id', 'question_id', 'answer', 'create_time', 'update_time']);
            }])->find($id)->toArray();
            if (!$question){
                throw new ModelNotFoundException('未找到该恋爱问题信息！');
            }
            // 提升问题回答层级到问题
            $question['answer'] = $question['answer'][0] ?? null;
            // 缓存该问题详情
            LoveQuestionCache::setUserLoveQuestById($this->user->id, $id, $question);
        }
        return $question;
    }

    /**
     * @todo 回答恋爱问题
     * @param Request $request
     * @param $id
     * @return bool
     * @throws ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function answerQuestion(Request $request, $id)
    {
        if (!$this->user->dummy){
            throw new BadRequestException('请先创建虚拟对象', Response::HTTP_FORBIDDEN);
        }
        $question = $this->loveQuestionModel->find($id);
        if (!$question){
            throw new ModelNotFoundException('未找到该恋爱问题信息！');
        }
        $data = [
            'question_id' => $id,
            'user_id' => $this->user->id,
            'answer' =>$request->post('answer', '')
        ];
        // 内容安全检测
        $is_safe_content = (new WechatService())->checkText($data['answer']);
        if ($is_safe_content['errcode'] != 0){
            throw new BadRequestException('内容含有违法违规内容');
        }
        $answer = $this->loveQuestionAnswerModel->where('user_id', '=', $this->user->id)->where('question_id', '=', $id)->find();
        // 通过tag清空问题缓存
        LoveQuestionCache::removeUserLoveQuestByTag($this->user->id);
        if ($answer) return $answer->save($data);
        Db::startTrans();
        try {
            // 新增问题回答
            $this->loveQuestionAnswerModel::create($data);
            // 增加分值
            $this->user->dummy->score->save(['total_score' => $this->user->dummy->score->total_score + self::ANSWER_QUESTION_SCORE]);
            Db::commit();
        } catch (\Exception $exception){
            Db::rollback();
            throw new ServiceUnavailableException('系统错误，请稍后再试');
        }
        return true;
    }
}
